package bfsalgorithm;

import java.util.*;

/**
 * 210.课程表II
 */
public class Exercise13 {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        int[] in = new int[numCourses]; // 用来记录每一个数据的入度
        Map<Integer,List<Integer>> edges = new HashMap<>(); // 用来进行建图
        // 建图
        for(int i = 0;i < prerequisites.length;i++) {
            int a = prerequisites[i][0],b = prerequisites[i][1];
            if(!edges.containsKey(b)) {
                edges.put(b,new ArrayList<>());
            }
            edges.get(b).add(a);
            in[a]++;
        }

        Queue<Integer> q = new LinkedList<>();
        for(int i = 0;i < numCourses;i++) {
            if(in[i] == 0) {
                q.add(i);
            }
        }

        int[] ret = new int[numCourses];
        int index = 0;
        while(!q.isEmpty()) {
            int t = q.poll();
            ret[index++] = t;
            for(int a : edges.getOrDefault(t,new ArrayList<>())) {
                in[a]--;
                if(in[a] == 0) {
                    q.add(a);
                }
            }
        }

        for(int i = 0; i < numCourses;i++) {
            if(in[i] != 0) {
                return new int[0];
            }
        }

        return ret;
    }
}
